package com.draemoncode.weixindb.server;

import com.draemoncode.weixindb.constant.AppConstant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public final class TelnetServer implements InitializingBean, DisposableBean{

    @Autowired
    private AppConstant appConstant;

    @Autowired
    private TelnetServerInitializer telnetServerInitializer;

    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Override
    public void afterPropertiesSet() throws Exception {
        final SslContext sslCtx = null;
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(telnetServerInitializer);
//            b.bind(appConstant.getCsPort()).sync().channel().closeFuture().sync();
            b.bind(appConstant.getCsPort()).sync();
            LoggerFactory.getLogger(TelnetServer.class).info("服务器启动成功, 端口:" + appConstant.getCsPort());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() throws Exception {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}